from urllib2 import Request, HTTPError, URLError, urlopen
from httplib import InvalidURL
import os, threading, re
from cStringIO import StringIO
import traceback
from string import lower, strip

bot_useragent = 'User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.7) Gecko/2009030422 Ubuntu/8.04 (hardy) Firefox/3.0.7'

def stripuni2utf8(name):
    if isinstance(name, unicode):
        name = name.encode('utf-8')
    return strip(name)

def clean_url(url):
    """url quotes unicode data out of urls"""
    url = stripuni2utf8(url)
    url = ''.join([urllib.quote(c) if ord(c) >= 127 else c for c in url])
    return url

def login_sina(username = '', password = "", cookie = "ck.cookie", logger = None, referer = None, retries = 1):
    global bot_useragent
    url = "'https://login.sina.com.cn/sso/login.php?username=" + username + "&password=" + password + "&returntype=TEXT'"
    url = clean_url(url)
    if referer:
        referer = clean_url(referer)
    command_str = "curl -k -s -D %s --user-agent \"%s\" --retry %d --max-time %d " % (cookie, bot_useragent, retries, 30, )
    if referer:
        command_str += " --referer " + referer
    command_str += url
    try:
        ppipe_curl = os.popen(command_str)
        content = ppipe_curl.read()
        ppipe_curl.close()
        return True
    except:
        sio = StringIO()
        traceback.print_exc(file=sio)
        if logger:
            logger.warn(sio.getvalue(), "fetch_url_sina()")
            logger.warn('fail to fetch_url_sina for ' + url)
        sio.close()
        return None
    finally:
        if 'ppipe_curl' in locals():
            ppipe_curl.close()

def fetch_url_sina(url, cookie = "ck.cookie", logger = None, referer = None, retries = 1):
    global bot_useragent
    url = clean_url(url)
    if referer:
        referer = clean_url(referer)
    command_str = "curl -s -e \"http://t.sina.com.cn\" -b %s --user-agent \"%s\" --retry %d --max-time %d " % (cookie, bot_useragent, retries, 30, )
    if referer:
        command_str += " --referer " + referer
    command_str += url
    try:
        ppipe_curl = os.popen(command_str)
        content = ppipe_curl.read()
        ppipe_curl.close()
        return content
    except:
        sio = StringIO()
        traceback.print_exc(file=sio)
        if logger:
            logger.warn(sio.getvalue(), "fetch_url_sina()")
            logger.warn('fail to fetch_url_sina for ' + url)
        sio.close()
        return None
    finally:
        if 'ppipe_curl' in locals():
            ppipe_curl.close()

def publish_message_sina(message, cookie = "ck.cookie", logger = None, referer = None, retries = 1):
    global bot_useragent
    url = "http://t.sina.com.cn/mblog/publish.php"
    url = clean_url(url)
    if referer:
        referer = clean_url(referer)
    command_str = "curl -s -d \"content=%s \" -e \"http://t.sina.com.cn\" -b %s --user-agent \"%s\" --retry %d --max-time %d " % (message, cookie, bot_useragent, retries, 30, )
    if referer:
        command_str += " --referer " + referer
    command_str += url
    try:
        ppipe_curl = os.popen(command_str)
        content = ppipe_curl.read()
        ppipe_curl.close()
        return content
    except:
        sio = StringIO()
        traceback.print_exc(file=sio)
        if logger:
            logger.warn(sio.getvalue(), "fetch_url_sina()")
            logger.warn('fail to fetch_url_sina for ' + url)
        sio.close()
        return None
    finally:
        if 'ppipe_curl' in locals():
            ppipe_curl.close()

def uploadpic(filename = "/home/iambest/space-03.jpg", cookie = "ck.cookie", logger = None, referer = None, retries = 1):
    global bot_useragent
    url = 'http://picupload.t.sina.com.cn/interface/pic_upload.php?marks=1&markstr=t.sina.com.cn/1687510427&s=rdxt&app=miniblog&cb=http://t.sina.com.cn/upimgback.html'
    url = clean_url(url)
    if referer:
        referer = clean_url(referer)
    command_str = "curl -F upload=@%s -v -s -e \"http://t.sina.com.cn\" -b %s --user-agent \"%s\" --retry %d --max-time %d " % (filename, cookie, bot_useragent, retries, 30, )
    if referer:
        command_str += " --referer " + referer
    command_str += url
    try:
        ppipe_curl = os.popen(command_str)
        content = ppipe_curl.read()
        ppipe_curl.close()
        return content
    except:
        sio = StringIO()
        traceback.print_exc(file=sio)
        if logger:
            logger.warn(sio.getvalue(), "fetch_url_sina()")
            logger.warn('fail to fetch_url_sina for ' + url)
        sio.close()
        return None
    finally:
        if 'ppipe_curl' in locals():
            ppipe_curl.close()

login_sina()
#publish_message_sina("fengyuncrawl")
c=uploadpic()
publish_message_sina("fengyuncrawl")
print c

